<template>
  <div class="section_box">
    <el-card>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="OPEN_DIALOG()"
      >
        添加品牌
      </el-button>

      <div class="table_section">
        <el-table :data="tableData" show-overflow-tooltip stripe border>
          <el-table-column
            label="序号"
            width="100px"
            type="index"
            align="center"
          />
          <el-table-column prop="tmName" label="品牌名称" width="150" />

          <el-table-column prop="logoUrl" label="品牌LOGO" min-width="200">
            <template #default="scope">
              <myImg :scr="scope.row.logoUrl"></myImg>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="150">
            <template #default="scope">
              <el-button
                type="primary"
                icon="Edit"
                size="small"
                @click="OPEN_DIALOG(scope.row.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="Delete"
                size="small"
                @click="DELETE_DIALOG(scope.row.id)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination_section">
        <el-pagination
          v-model:current-page="form.pageNo"
          v-model:page-size="form.limit"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="prev, pager, next,jumper, ->,sizes,total "
          :total="total"
          @size-change="GET_LIST"
          @current-change="GET_LIST"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800">
      <el-form :model="trademarkParams" ref="ruleFormRef" :rules="rules">
        <el-form-item
          label="品牌名字"
          :label-width="formLabelWidth"
          prop="tmName"
        >
          <el-input v-model="trademarkParams.tmName" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="品牌LOGO"
          :label-width="formLabelWidth"
          prop="logoUrl"
        >
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="CLOSE_DIALOG">取消</el-button>
          <el-button type="primary" @click="ADDUPDATE_DIALOG">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'trademark',
}
</script>
<script setup lang="ts">
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

import { onMounted, ref, reactive } from 'vue'
import {
  resHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeletTrademark,
} from '@/api/product'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/type'

import { publicConfirm } from '@/utils/handleData'

interface RuleForm {
  id?: number
  tmName: string
  logoUrl: string
}
onMounted(() => {
  GET_LIST()
})

const ruleFormRef = ref<FormInstance>()
let total = ref<number>(1)
let form = reactive({
  pageNo: 1,
  limit: 10,
})

const dialogVisible = ref(false)
let dialogTitle = ref('')
const formLabelWidth = '140px'

let tableData = reactive<Records>([])
const trademarkParams_init = { id: 0, tmName: '', logoUrl: '' }
let trademarkParams = reactive<TradeMark>({ ...trademarkParams_init })

const GET_LIST = async () => {
  let result: TradeMarkResponseData = await resHasTrademark(form)
  if (result.code == 200) {
    total.value = result.data.total
    tableData = result.data.records
  }
}

const OPEN_DIALOG = (id = 0) => {
  //   console.log(id)
  INIT_DIALOG()
  if (id > 0) {
    //修改
    dialogTitle.value = '修改品牌'
    const found = tableData.find((item) => item.id === id)
    if (found) {
      Object.assign(trademarkParams, found)
    }
  } else {
    // 添加
    dialogTitle.value = '添加品牌'
  }
  dialogVisible.value = true
}
const CLOSE_DIALOG = () => {
  dialogVisible.value = false
}

const INIT_DIALOG = () => {
  Object.assign(trademarkParams, trademarkParams_init)
  if (!ruleFormRef.value) return
  ruleFormRef.value.clearValidate('logoUrl')
  ruleFormRef.value.clearValidate('tmName')
}

const rules = reactive<FormRules<RuleForm>>({
  tmName: [
    {
      required: true,
      trigger: 'change',
      validator: validatorName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: 'change',
      validator: validatorLogo,
    },
  ],
})

function validatorName(_rule: any, value: any, callback: any) {
  //   console.log(a, b, c)
  if (value.length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称应该大于等于2位'))
  }
}
function validatorLogo(_rule: any, value: any, callback: any) {
  //   console.log(a, b, c)
  if (value.length > 0) {
    callback()
  } else {
    callback(new Error('请上传图片'))
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  console.log(response)
  console.log(uploadFile)
  trademarkParams.logoUrl = URL.createObjectURL(uploadFile.raw!)

  ruleFormRef.value?.clearValidate('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const ADDUPDATE_DIALOG = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  let type = '添加'
  if (trademarkParams.id) {
    type = '修改'
  }
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: `${type}成功`,
    })
    GET_LIST()
  } else {
    ElMessage({
      type: 'error',
      message: `${type}成功`,
    })
  }
  CLOSE_DIALOG()
}
// 删除对话框
const DELETE_DIALOG = async (id = 0) => {
  const flag = await publicConfirm({
    title: '提示',
    content: '确认删除该品牌？',
  })
  let type = '删除'
  if (flag) {
    let result: any = await reqDeletTrademark(id)
    if (result.code == 200) {
      ElMessage({
        type: 'success',
        message: `${type}成功`,
      })
      GET_LIST()
    } else {
      ElMessage({
        type: 'error',
        message: `${type}失败`,
      })
    }
  } else {
    ElMessage({
      type: 'info',
      message: `取消${type}`,
    })
  }
  CLOSE_DIALOG()
}
</script>

<style scoped lang="scss">
.table_section {
  margin: 10px 0;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
